package com.tao.service;


import com.tao.dto.*;
import com.tao.entity.Account;
import com.tao.entity.Member;
import com.tao.entity.RegisterCode;
import com.tao.entity.User;
import com.tao.repository.AccountRepository;
import com.tao.repository.MemberRepository;
import com.tao.repository.RegisterCodeRepository;
import com.tao.util.BeanCopierUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class MemberService {
    @Autowired
    private MemberRepository memberRepository;

    @Autowired
    private RegisterCodeRepository registerCodeRepository;
    @Autowired
    private AccountRepository accountRepository;


    public Member insert(Member member) {
        memberRepository.save(member);
        return member;
    }

    public Member findById(Integer id) {
        Member member = memberRepository.findById(id).get();
        return member;
    }

    public PageResult findAll(Member member, Integer pageNo, Integer pageSize) {
        Page<Member> all = memberRepository.findAll(Example.of(member), PageRequest.of(pageNo - 1, pageSize));
        return PageResult.PageResultBuild(all.getTotalElements(), all.getContent());
    }

    public void delete(Integer id) {
        memberRepository.deleteById(id);
    }

    public MyResult login(Member member) {
        Member result = memberRepository.findByUserNameAndPasswordAndAndDeviceCode(member.getUserName(), member.getPassword(), member.getDeviceCode());
        if (result != null) {
            List<Account> all = accountRepository.findAll();
            LoginResult loginResult=BeanCopierUtils.copy(result,LoginResult.class);
            loginResult.setVekey(all.get(0).getVekey());
            loginResult.setVeCard(all.get(0).getVeCard());
            loginResult.setPid(all.get(0).getPid());
            return new SuccessResult("操作成功",loginResult);
        } else {
            return new ExceptionResult("账号或密码错误");
        }
    }


    public MyResult register(Member member) {
        RegisterCode byCode = registerCodeRepository.findByCode(member.getRegisterCode());
        if (byCode==null){
            return new ExceptionResult("注册码不存在");
        }

        List<Member> allByUserName = memberRepository.findAllByUserName(member.getUserName());
        if (allByUserName.size()>0){
            return new ExceptionResult("该用户名已存在");
        }
        member.setValidTime(new Date());
        memberRepository.saveAndFlush(member);
        registerCodeRepository.deleteById(byCode.getId());
        return new SuccessResult("操作成功",member);
    }
}
